//
//  ExSafariExtensionViewController.m
//  OC-Example
//
//  Created by lcj on 2020/9/8.
//  Copyright © 2020 apang.men. All rights reserved.
//

#import "ExSafariExtensionViewController.h"
#import <SafariServices/SafariServices.h>
@interface ExSafariExtensionViewController ()
@property (nonatomic, strong) NSURL * secureAppGroupPersistentStoreURL;
@property (nonatomic, strong) UIActivityIndicatorView * indicator;
@end

@implementation ExSafariExtensionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"Safari 广告拦截";
    UIButton * checkStatusBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [checkStatusBtn setTitle:@"检查状态" forState:UIControlStateNormal];
    [checkStatusBtn addTarget:self action:@selector(onClickcheckStatusBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkStatusBtn];
    checkStatusBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:checkStatusBtn attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:checkStatusBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-80]];
    
    UIButton * reloadBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [reloadBtn setTitle:@"重新加载" forState:UIControlStateNormal];
    [reloadBtn addTarget:self action:@selector(onClickReloadBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:reloadBtn];
    reloadBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:reloadBtn attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:reloadBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:checkStatusBtn attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20]];
    
    UIButton * downLoadBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [downLoadBtn setTitle:@"在线更新资源" forState:UIControlStateNormal];
    [downLoadBtn addTarget:self action:@selector(onClickDownLoadBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:downLoadBtn];
    downLoadBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:downLoadBtn attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:downLoadBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:reloadBtn attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20]];
    
}


- (void)onClickcheckStatusBtn {
    if (@available(iOS 10, *)) {
        __weak typeof(self) weakSelf = self;
        [SFContentBlockerManager getStateOfContentBlockerWithIdentifier:@"men.apang.Example.BookAdBlocker" completionHandler:^(SFContentBlockerState * _Nullable state, NSError * _Nullable error) {
            NSLog(@"status:%@ error:%@",(state.enabled)?@"开启":@"关闭",error);
            [weakSelf showMessage:[NSString stringWithFormat:@"扩展%@,%@",(state.enabled)?@"开启":@"关闭",error]];
        }];
    }
}

- (void)onClickReloadBtn {
    
    if (@available(iOS 9.0, *)) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData * data = [NSData dataWithContentsOfFile:[weakSelf.secureAppGroupPersistentStoreURL path]];
            if (data.length > 0) {
                NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"%@",json);
            }
        });
        [SFContentBlockerManager reloadContentBlockerWithIdentifier:@"men.apang.Example.BookAdBlocker" completionHandler:^(NSError * _Nullable error) {
            NSLog(@"reload:%@",error);
            [weakSelf showMessage:[NSString stringWithFormat:@"扩展重新加载%@,%@",(error == nil)?@"成功":@"失败",error]];
        }];
       
    }
}

- (void)onClickDownLoadBtn {
    [self download];
}

- (void)download {
    [self.indicator startAnimating];
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData * data = [NSData dataWithContentsOfURL:[weakSelf blockerListUrl]];
        if (data.length > 0) {
            [data writeToURL:weakSelf.secureAppGroupPersistentStoreURL atomically:YES];
            NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@",json);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.indicator stopAnimating];
            [weakSelf showMessage:[NSString stringWithFormat:@"下载:%@",(data.length> 0)?@"成功":@"失败"]];
        });
    });
}

- (void)showMessage:(NSString *)message {
    if ([NSThread currentThread].isMainThread == NO) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertVC addAction:action];
            [self presentViewController:alertVC animated:YES completion:nil];
        });
    } else {
        UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertVC addAction:action];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (NSURL *)secureAppGroupPersistentStoreURL {
    if (_secureAppGroupPersistentStoreURL == nil) {
        NSFileManager * fileManager = [NSFileManager defaultManager];
        NSURL * groupDictionary = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.men.apang.Example"];
        _secureAppGroupPersistentStoreURL = [groupDictionary URLByAppendingPathComponent:@"blockerList.json"];
    }
    return _secureAppGroupPersistentStoreURL;
}

- (NSURL *)blockerListUrl {
    return [NSURL URLWithString:@"https://gitee.com/doule/iOS-Example/raw/master/BookAdBlocker/blockerList.json"];
}

- (UIActivityIndicatorView *)indicator {
    if (_indicator == nil) {
        _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        CGRect frame = [UIScreen mainScreen].bounds;
        [_indicator setFrame:CGRectMake((CGRectGetWidth(frame) - 100.0)/2.0, (CGRectGetHeight(frame) - 100.0)/2.0, 100, 100)];
        _indicator.color = [UIColor whiteColor];
        _indicator.backgroundColor = [UIColor lightGrayColor];
    }
    return _indicator;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
